/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package myApp.KnorrAndroid.lib.network.http;

import java.io.UnsupportedEncodingException;

/**
 * @class  HTTPResponse
 * @author SoaN
 * @since Aug 5, 2010
 * Copyright KunKun.Vn �2010 - All rights reserved.
 * VIETTEL PROPRIETARY/CONFIDENTIAL.
 */
public class HTTPResponse extends HTTPMessage implements DataReceiver{
	static final int REGULAR_ALLOC = 32;
	static final int BUFFER_SIZE = 512;
    HTTPRequest request;
    
    int nByteReceive = 0;
    
    public HTTPRequest getRequest() {
        return request;
    }
    
    public HTTPResponse(HTTPRequest request) {
    	this.request = request;
		setContentType(HTTPResponse.CONTENT_TEXT);
		setAction(request.getAction());
		setId(request.getId());
		setTitle(request.getTitle());
		setUserData(request.getUserData());
		setObserver(request.getObserver());
    }
    
    public void setRequest(HTTPRequest request) {
        this.request = request;
    }

    public boolean isAlive() {
        boolean ret = true;
        if (this.request != null) {
            ret = request.isAlive();
        }
        return ret;
    }

    public HTTPResponse() {
        super();
    }

	/* (non-Javadoc)
	 * @see com.viettel.kunkun.kunkunlibrary.network.http.DataReceiver#onDataComing(byte[], int, int)
	 */
	@Override
	public void onDataComing(byte[] data, int startIndex, int length) {
		// TODO Auto-generated method stub
		if (dataBinary == null) {
			dataBinary = new byte[BUFFER_SIZE];
		}
		
		if (dataBinary.length < nByteReceive + length) {
			int newSize = Math.max(nByteReceive + length, dataBinary.length + REGULAR_ALLOC);
			byte[] temp = dataBinary;
			dataBinary = new byte[newSize];
			for (int i = 0, n = temp.length; i < n; i++){
				dataBinary[i] = temp[i];
			}
		}
		
		for (int i = 0; i < length; i++){
			dataBinary[nByteReceive + i] = data[startIndex + i];
		}
		nByteReceive += length;
	}

	/* (non-Javadoc)
	 * @see com.viettel.kunkun.kunkunlibrary.network.http.DataReceiver#onComplete()
	 */
	@Override
	public void onComplete() {
		// TODO Auto-generated method stub
		if (request != null && HTTPRequest.DATA_TYPE_TEXT.equals(request.getDataTypeReceive())){
			try {
				if (dataBinary != null){
					dataText = new String(dataBinary, "UTF8");
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				dataBinary = null;
			}
		}
	}
}
